import { defineStore } from 'pinia';
import { Session } from '/@/utils/storage';

import { useLoginApi } from '/@/api/login';

/**
 * 用户信息
 * @methods setUserInfos 设置用户信息
 */
export const useUserInfo = defineStore('userInfo', {
	state: (): UserInfosState => ({
		userInfos: {
			userName: '',
			tenantName: '',
			photo: '',
			time: 0,
			roles: [],
			authBtnList: [],
		},
	}),
	actions: {
		async setUserInfos() {
			// 存储用户信息到浏览器缓存
			if (Session.get('userInfo')) {
				this.userInfos = Session.get('userInfo');
			} else {
				// const userInfos = <UserInfos>await this.getApiUserInfo();
				this.userInfos = <UserInfos>await this.getApiUserInfo();
			}
		},
		// 模拟接口数据
		// https://gitee.com/lyt-top/vue-next-admin/issues/I5F1HP
		async getApiUserInfo() {
			// 获取用户基本信息和权限等信息
			return new Promise((resolve) => {
				useLoginApi()
					.getUserInfo()
					.then((res) => {
						const userInfoData = res.data;
						// 用户信息
						const userInfos = {
							userName: userInfoData.userName,
							tenantName: userInfoData.tenantName,
							photo:
								userInfoData.userName === 'admin'
									? 'https://img.picgo.net/2023/05/17/IMG_55603af79ed833c07764.jpeg'
									: 'https://img.picgo.net/2023/05/17/IMG_55629e7c4e0116bb2e43.jpeg',

							time: new Date().getTime(),
							roles: userInfoData.roles.map((item: any) => item.roleSign),
							authBtnList: userInfoData.authBtnList || [],
						};
						Session.set('userInfo', userInfos);
						resolve(userInfos);
					});
			});
		},
	},
});
